﻿using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Const;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.Workflow.Interface;
using Kingdee.BOS.Workflow.Models.Chart;
using Kingdee.BOS.Workflow.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.DzWorkflow.Dz
{
    [Description("Dz:审批动作服务插件实现"), HotUpdate]
    public class ApprovalInfoServicePlugIn : AbstractOperationServicePlugIn
    {
        private const string KEY_User1 = "FUserId1_Id";
        private const string KEY_Opinion1 = "FRemarks1";
        private const string KEY_TaskTitle1 = "FTaskTitle1";
        private const int KEY_FirstNodeId = 5;
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            /*
             * 先在操作上配置服务插件，然后在节点的审批项上配置操作。
             * 对于有审核操作的终审节点，可以在审核操作上配置服务插件。
             * 打开BOS设计器中目标单据的操作列表，在审核操作上配置服务插件
             * 在终审节点审批项上配置审核操作：
             * 对于没有审核操作的普通节点，可以在审批项上配置空操作，然后在空操作上配置服务插件
             * 打开BOS设计器中目标单据的操作列表，新增用于输出审批人的空操作，并配置服务插件：
             * 在普通节点审批项上配置该空操作：
             */
            base.EndOperationTransaction(e);
            var operationNumber = this.FormOperation.Operation;
            // 获取流程任务信息
            var activityCollection = this.Option.GetVariableValue<ObjectActivityInstanceCollection>(BOSConst.CST_KEY_WfActivityInstance, null);
            if (activityCollection != null)
            {
                IMetaDataService metaService = ServiceFactory.GetMetaDataService(this.Context);
                IViewService viewService = ServiceFactory.GetViewService(this.Context);
                List<DynamicObject> rowList = new List<DynamicObject>();
                // 每个任务传入一个ObjectActivityInstance对象，批量审批任务时会传入多个对象
                foreach(var actRow in activityCollection)
                {
                    //获取当前最新流程实例id
                    //string cprocInstId = WorkflowChartServiceHelper.GetProcInstIdByBillInst(this.Context, actRow.ObjectFormId, actRow.ObjectKeyValue);
                    //获取所有节点
                    List<ChartActivityInfo> activityInfos = WorkflowChartServiceHelper.GetProcessRouter(this.Context, actRow.ActivityInstance.ProcessInstance.ProcessInstanceId);
                    //当前节点
                    var chartActivityInfos = activityInfos.Where(w => w.ActionDetails.Where(w1 => w1.AssignId.EqualsIgnoreCase(actRow.ActivityInstance.ActivityInstanceId)).Count() > 0);
                    //新节点
                    ChartActivityInfo chartActivityInfo = activityInfos.Last();


                    // 本例演示获取当前处理人的信息（每个任务可能有多个处理人，所有处理人存储在ReceiverList属性中）
                    IActivityInstance actInstance = actRow.ActivityInstance;
                    var currentReceiver = actInstance.CurrentReceiver;
                    // 加载单据数据
                    FormMetadata rowMeta = metaService.Load(this.Context, actRow.ObjectFormId, true) as FormMetadata;
                    var rowData = viewService.LoadSingle(this.Context, actRow.ObjectKeyValue, rowMeta.BusinessInfo.GetDynamicObjectType());
                    // 根据节点ID把审批人等信息输出到相应字段上，比如一级审核节点（如何查询节点ID参见下文）的审批人输出到FUserId1字段上
                    if (actInstance.ActivityDefineId == KEY_FirstNodeId && currentReceiver != null)

                    {
                        // 可以输出审批人、意见、所选审批项、审批时间、任务标题信息
                        //rowData[KEY_User1] = currentReceiver.ReceiverUserId;
                        //rowData[KEY_Opinion1] = currentReceiver.ActionOpinion;
                        //rowData[KEY_TaskTitle1] = currentReceiver.TaskTitle;// 任务标题属性，预计在8月后的补丁支持
                    }
                    rowList.Add(rowData);
                }
                if (rowList.Count > 0)
                {
                    ISaveService saveService = ServiceFactory.GetSaveService(this.Context);
                    saveService.Save(this.Context, rowList.ToArray());
                }
            }
        }
    }
}
